package stdio.costa.imoca.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;

import com.sun.jersey.api.container.MappableContainerException;

import stdio.costa.imoca.exception.AuthenticationFailedException;
import stdio.costa.imoca.model.MocaUser;
import stdio.costa.imoca.spi.MocaUserSpi;

public class SecurityCheckFilter implements Filter {

	protected FilterConfig filterConfig = null;

	private String redirectURL;

	private List<String> notCheckURLList = new ArrayList<String>();

	@Autowired
	private MocaUserSpi mocaUserSpi;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	@Override
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
//		if (!checkRequestURIInFilterList(request)) {
//			if (!validateAuthorization(request)) {
//				throw new MappableContainerException(new AuthenticationFailedException());
//			}
//		}

		chain.doFilter(request, response);
	}

	private boolean checkRequestURIInFilterList(HttpServletRequest request) {
		String uri = request.getServletPath()
				+ (request.getPathInfo() == null ? "" : request.getPathInfo());
		return notCheckURLList.contains(uri);
	}

	private boolean validateAuthorization(HttpServletRequest request) {
		String accessTokenCode = (String) request.getParameter("accessToken");

		if (accessTokenCode == null) {
			return false;
		}

		MocaUser mocaUser = mocaUserSpi
				.getMocaUserByAccessToken(accessTokenCode);

		if (mocaUser == null) {
			return false;
		}

		request.getServletContext().setAttribute("mocaUser", mocaUser);

		return true;
	}

	@Override
	public void destroy() {

	}

	public List<String> getNotCheckURLList() {
		return notCheckURLList;
	}

	public void setNotCheckURLList(List<String> notCheckURLList) {
		this.notCheckURLList = notCheckURLList;
	}

	public String getRedirectURL() {
		return redirectURL;
	}

	public void setRedirectURL(String redirectURL) {
		this.redirectURL = redirectURL;
	}
}
